package br.com.trumah.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import br.com.trumah.dao.interfaces.BeneficiarioDAO;
import br.com.trumah.model.Beneficiario;
import br.com.trumah.utils.HibernateUtil;

public class BeneficiarioDAOImpl implements BeneficiarioDAO {
	
	private Session session = null;
	private Transaction t = null;

	@Override
	public void salvar(Beneficiario beneficiario) {

		try{

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.save(beneficiario);
			t.commit();
			
		} catch (HibernateException ex) {
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		
	}

	@Override
	public Beneficiario obterBeneficiario(long id) {
		
		Beneficiario beneficiario = null;
		
		try{
			
			session = HibernateUtil.getSessionFactory().openSession();
			beneficiario = (Beneficiario) session.load(Beneficiario.class, id);

		} catch (HibernateException ex){
			
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return beneficiario;
		
	}

	@Override
	public List<Beneficiario> listar() {

		List<Beneficiario> lista = null;
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			lista = session.createQuery("from Beneficiario").list();
			t.commit();
			
		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}
		
		return lista;
		
	}

	@Override
	public void remover(Beneficiario beneficiario) {

		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.delete(beneficiario);
			t.commit();

		} catch (HibernateException ex) {
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			session.close();
		}
		

	}

	@Override
	public void atualizar(Beneficiario beneficiario) {
		
		try{

			session = HibernateUtil.getSessionFactory().openSession();
			t = session.beginTransaction();
			session.update(beneficiario);
			t.commit();

		} catch (HibernateException ex){
			
			t.rollback();
			ex.printStackTrace();
			
		} finally {
			
			session.close();
			
		}

	}

}
